package com.movitech.mobile.cz.base.purchase.bizservice.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.movitech.mobile.cz.base.common.aop.ServiceThrowable;
import com.movitech.mobile.cz.base.common.license.LicenseUtil;
import com.movitech.mobile.cz.base.common.util.*;
import com.movitech.mobile.cz.base.common.utils.IdGen;
import com.movitech.mobile.cz.base.modules.config.*;
import com.movitech.mobile.cz.base.modules.controller.RestReturnResult;
import com.movitech.mobile.cz.base.purchase.bizservice.OuterWorkFlowService;
import com.movitech.mobile.cz.base.purchase.bizvo.*;
import com.movitech.mobile.cz.base.purchase.bizvo.outer.*;
import com.movitech.mobile.cz.base.purchase.entity.*;
import com.movitech.mobile.cz.base.purchase.entity.ext.ExtWFlowForm;
import com.movitech.mobile.cz.base.purchase.entity.ext.ExtWFlowFormExtMng;
import com.movitech.mobile.cz.base.purchase.entity.ext.ExtWFlowFormExtSubMng;
import com.movitech.mobile.cz.base.purchase.entity.ext.PlanInvitationResponseVO;
import com.movitech.mobile.cz.base.purchase.mapper.ext.ExtWFlowFormMapper;
import com.movitech.mobile.cz.base.purchase.service.*;
import com.movitech.mobile.cz.base.supplier.entity.SCommentConfig;
import com.movitech.mobile.cz.base.supplier.entity.SHistoryComment;
import com.movitech.mobile.cz.base.supplier.entity.SMyDeals;
import com.movitech.mobile.cz.base.supplier.entity.SSuppliers;
import com.movitech.mobile.cz.base.supplier.service.SCommentConfigService;
import com.movitech.mobile.cz.base.supplier.service.SHistoryCommentService;
import com.movitech.mobile.cz.base.supplier.service.SMyDealsService;
import com.movitech.mobile.cz.base.supplier.service.SSuppliersService;
import com.movitech.mobile.cz.base.sys.bizvo.AttachmentVO;
import com.movitech.mobile.cz.base.sys.bizvo.NoticeResponseVO;
import com.movitech.mobile.cz.base.sys.entity.SAttachment;
import com.movitech.mobile.cz.base.sys.entity.SMessages;
import com.movitech.mobile.cz.base.sys.entity.ext.ExtSAttachment;
import com.movitech.mobile.cz.base.sys.entity.ext.ExtSAttachmentReq;
import com.movitech.mobile.cz.base.sys.service.SAttachmentService;
import com.movitech.mobile.cz.base.sys.service.SMessagesService;
import com.movitech.mobile.cz.base.util.UserUtils;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.BeanWrapper;
import org.springframework.beans.BeanWrapperImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * Created by robie.cao on 2018/4/25.
 */
@Service("outerWorkFlowService")
public class OuterWorkFlowServiceImpl implements OuterWorkFlowService{

    @Autowired
    private SAttachmentService sAttachmentService;

    @Autowired
    private ExtWFlowFormMapper extWFlowFormMapper;

    @Autowired
    private WFlowFormSupplierEntryService wFlowFormSupplierEntryService;

    @Autowired
    private SSuppliersService sSuppliersService;

    @Autowired
    private WFlowFormSuppliersQuestionService wFlowFormSuppliersQuestionService;

    @Autowired
    private SMyDealsService sMyDealsService;

    @Autowired
    private SMessagesService sMessagesService;

    @Autowired
    private WFlowFormExtMngService wFlowFormExtMngService;

    @Autowired
    private WFlowFormExtSubMngService wFlowFormExtSubMngService;

    @Autowired
    private SHistoryCommentService sHistoryCommentService;
    @Autowired
    private WFlowFormTimeNodeService wFlowFormTimeNodeService;
    @Autowired
    private WFlowFormService wFlowFormService;
    @Autowired
    private SCommentConfigService sCommentConfigService;
    @Autowired
    private WFlowFormSupplierAttachService wFlowFormSupplierAttachService;
    @Autowired
    private WFlowFormSendBidService wFlowFormSendBidService;

    @Autowired
    private WFlowFormInquiringBidService wFlowFormInquiringBidService;
    @Autowired
    private WFlowFormBidNoticeThanksService wFlowFormBidNoticeThanksService;
    @Autowired
    private WFlowFormBackBidService wFlowFormBackBidService;
    @Autowired
    private WFlowFormAddendumReferersService wFlowFormAddendumReferersService;
    @Autowired
    private WFlowFormQuestionAnswerService wFlowFormQuestionAnswerService;

    /**
     * 招标管网
     * @param vo
     * @return
     */
    @Override
    public Page<ExtWFlowFormExtMng> getBidManageData(Page<ExtWFlowFormExtMng> page , BidManageReqVo vo) {
        vo.setSupplierId(UserUtils.getOuterCurrentUserVO().getSuppliersId());
        //vo.setSupplierId("282a943500d24ccf88d20ab0e5759399");
       return wFlowFormExtMngService.selectPage(page,vo);

    }

    /**
     * 招标项详情
     * @param id
     * @return
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED, readOnly = false, rollbackForClassName = {"RuntimeException", "Exception"})
    public BidItemDetailVo purchaseItemDetail(String id) throws Exception {
        BidItemDetailVo bidItemDetailVo = new BidItemDetailVo();
        WFlowFormExtMng wFlowFormExtMng = wFlowFormExtMngService.selectById(id);
        if(wFlowFormExtMng==null){
            wFlowFormExtMng =  wFlowFormExtMngService.selectByFormIdAnSupplierId(id,UserUtils.getOuterCurrentUserVO().getSuppliersId());
        }

        WFlowForm wFlowForm = wFlowFormService.selectById(wFlowFormExtMng.getFlowFormId());
        WFlowFormTimeNode wFlowFormTimeNode = wFlowFormTimeNodeService.selectByFlowFormId(wFlowFormExtMng.getFlowFormId());
        bidItemDetailVo.setWFlowFormTimeNode(wFlowFormTimeNode);

        ExtWFlowFormExtMng extWFlowFormExtMng = new ExtWFlowFormExtMng();
        BeanUtils.copyProperties(wFlowFormExtMng,extWFlowFormExtMng);
        extWFlowFormExtMng.setAbortiveFlag(wFlowForm.getAbortiveFlag());
        extWFlowFormExtMng.setCalibrationFlag(wFlowForm.getCalibrationFlag());
        bidItemDetailVo.setFlowFormExtMng(extWFlowFormExtMng);
        List<WFlowFormExtSubMng> wFlowFormExtSubMngs = wFlowFormExtSubMngService.getByParentId(wFlowFormExtMng.getId());
        List<ExtWFlowFormExtSubMng> extWFlowFormExtSubMngs = ListObjCopyUtil.copyTo(wFlowFormExtSubMngs,ExtWFlowFormExtSubMng.class);
        bidItemDetailVo.setFlowFormExtSubMngs(extWFlowFormExtSubMngs);
        for(ExtWFlowFormExtSubMng extWFlowFormExtSubMng:extWFlowFormExtSubMngs){
            Integer actionStatus = extWFlowFormExtSubMng.getActionStatus();
            if(actionStatus==WFlowFormExtSubEnum.STATUS_4_2.getCode()&&isRightTime(wFlowFormTimeNode.getBackBid(),wFlowFormTimeNode.getBackBidDelay())){
                extWFlowFormExtSubMng.setTimeStatus(CommonConstants.YES_INTEGER);
            }else if(actionStatus==WFlowFormExtSubEnum.STATUS_4_6.getCode()&&isRightTime(wFlowFormTimeNode.getTwoRoundBackBid(),wFlowFormTimeNode.getTwoRoundBackBidDelay())){
                extWFlowFormExtSubMng.setTimeStatus(CommonConstants.YES_INTEGER);
            }else if(actionStatus==WFlowFormExtSubEnum.STATUS_4_8.getCode()&&isRightTime(wFlowFormTimeNode.getBusinessNegoteReturn(),wFlowFormTimeNode.getBusinessNegoteReturnDelay())){
                extWFlowFormExtSubMng.setTimeStatus(CommonConstants.YES_INTEGER);
            }else if(actionStatus==WFlowFormExtSubEnum.STATUS_4_10.getCode()&&isRightTime(wFlowFormTimeNode.getBidEvaluation(),wFlowFormTimeNode.getBidEvaluationDelay())){
                extWFlowFormExtSubMng.setTimeStatus(CommonConstants.YES_INTEGER);
            }
            extWFlowFormExtSubMng.setHistoryComments(sHistoryCommentService.findByModelTypeAndRelatedId(null,wFlowFormExtMng.getFlowFormId(),extWFlowFormExtSubMng.getId()));
        }

        return bidItemDetailVo;
    }

    boolean isRightTime(Date endTime,Date delayTime){
        LicenseUtil.INSTANCE.validate();
        boolean flag = false;
        Long now = DateUtils.getNow().getTime();
        if(endTime==null)
            flag = true;
        else if(now<endTime.getTime()){
            flag = true;
        }else if(delayTime!=null&&delayTime.getTime()>now)
            flag = true;

        return flag;
    }

    /**
     * 邀请函详情
     * @param formId
     */
    @Override
    public InvitationDetailResponse invitationDetail(String formId) {
        LicenseUtil.INSTANCE.validate();
        InvitationDetailResponse invitationDetailResponse = new InvitationDetailResponse();
        invitationDetailResponse.setDealBisVo(getDealBisVo(formId));
        WFlowForm wFlowForm = wFlowFormService.selectById(formId);
//        if(!wFlowForm.getFlowFormSubStatus().contains(WorkFlowLineStatusEnum.LINE_STATUS_SUPPLIER_ENTRY.getCode()+"")){
//            throw new RuntimeException("当前不是可回复邀请函状态",new ServiceThrowable());
//        }
        invitationDetailResponse.setCompanyName(UserUtils.getOuterCurrentUserVO().getCompanyName());
        invitationDetailResponse.setPurchaseItemName(wFlowForm.getPurchaseItemName());
        invitationDetailResponse.setOriginatorUser(wFlowForm.getOriginatorUser());
        invitationDetailResponse.setBidBounds(wFlowForm.getBidBounds());
        invitationDetailResponse.setPayeeUnit(wFlowForm.getPayeeUnit());
        invitationDetailResponse.setRemittanceAccount(wFlowForm.getRemittanceAccount());
        invitationDetailResponse.setOpenedBank(wFlowForm.getOpenedBank());
        return invitationDetailResponse;
    }

    /**
     * 招标下载列表
     * @param vo
     * @return
     */
    @Override
    public BidFileDownRspVo bidFileList(BidFileDownReqVo vo) {
        BidFileDownRspVo bidFileDownRspVo = new BidFileDownRspVo(getDealBisVo(vo.getFormId()));
        ExtSAttachmentReq sAttachment = new ExtSAttachmentReq();
        sAttachment.setDelFlag(CommonConstants.DEL_FLAG_NORMAL);
        sAttachment.setFormId(vo.getFormId());
        LicenseUtil.INSTANCE.validate();
        List<Integer> types = Lists.newArrayList();
        types.add(AttachmentTypeEnum.ATTACHMENT_TYPE_16.getCode());
        types.add(AttachmentTypeEnum.ATTACHMENT_TYPE_17.getCode());
        types.add(AttachmentTypeEnum.ATTACHMENT_TYPE_18.getCode());
        types.add(AttachmentTypeEnum.ATTACHMENT_TYPE_19.getCode());
        types.add(AttachmentTypeEnum.ATTACHMENT_TYPE_46.getCode());
        sAttachment.setTypes(types);
        sAttachment.setUserId(UserUtils.getOuterCurrentUserVO().getSuppliersId());
        bidFileDownRspVo.setAttachments(sAttachmentService.getExtByEntity(sAttachment));
        return bidFileDownRspVo;
    }

    /**
     * 附件下载
     * @param vo
     * @return
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED, readOnly = false, rollbackForClassName = {"RuntimeException", "Exception"})
    public DownRspVo bidFileDown(AttachDownVo vo) {
        if(StringUtils.isEmpty(vo.getFormId()))
            throw new RuntimeException("参数异常",new ServiceThrowable());
        DownRspVo downRspVo = new DownRspVo();
        String supllierId = UserUtils.getOuterCurrentUserVO().getSuppliersId();
        Date now  = null;
        boolean downCommon = true;
        LicenseUtil.INSTANCE.validate();
        if(vo.getType()==AttachmentTypeEnum.ATTACHMENT_TYPE_16.getCode()||vo.getType()==AttachmentTypeEnum.ATTACHMENT_TYPE_17.getCode()||
                vo.getType()==AttachmentTypeEnum.ATTACHMENT_TYPE_18.getCode()|| vo.getType()==AttachmentTypeEnum.ATTACHMENT_TYPE_19.getCode()
                || vo.getType()==AttachmentTypeEnum.ATTACHMENT_TYPE_46.getCode()){//发标
            now = wFlowFormSendBidService.setDowned(vo.getFormId(),supllierId);
            if(now!=null){
                WFlowFormExtMng wFlowFormExtMng = wFlowFormExtMngService.selectByFormIdAnSupplierId(vo.getFormId(),supllierId);
                wFlowFormExtMng.setFlowFormStatus(WFlowFormExtEnum.STATUS_4.getCode()+"");
                wFlowFormExtMng.setBidDownloadFlag(CommonConstants.YES_INTEGER);
                wFlowFormExtMngService.updateById(wFlowFormExtMng);
                List<WFlowFormExtSubMng> wFlowFormExtSubMngs = wFlowFormExtSubMngService.getByParentId(wFlowFormExtMng.getId());
                for(WFlowFormExtSubMng wFlowFormExtSubMng:wFlowFormExtSubMngs){
                    sHistoryCommentService.saveSHistoryComment(buildCommonHistory(vo.getFormId(),wFlowFormExtSubMng.getId(),
                            HistoryCommentModelTypeEnum.HistoryCommentModelType26.getCode(), "",
                            PurchaseActionNameEnum.PURCHASE_PLAN_5_5.getDesc(), PurchaseNodeEnum.NODE_9_1.getDesc(), 0,PurchaseCommonEnum.OUTER_PROCESS_STATUS_1.getCode(),false));
                }

                SMyDeals sMyDeals = new SMyDeals();
                sMyDeals.setRelatedId(vo.getFormId());
                sMyDeals.setUserId(supllierId);
                sMyDeals.setActionType(MyDealActionTypeEnum.BIDS_DOWN_OUT.getCode());
                sMyDealsService.doneByEntityAndUsers(sMyDeals,null,"已处理");
            }else now = DateUtils.getNow();

        }else if(vo.getType()==AttachmentTypeEnum.ATTACHMENT_TYPE_41.getCode()){//二轮标书下载
            WFlowFormExtMng wFlowFormExtMng = wFlowFormExtMngService.selectByFormIdAnSupplierId(vo.getFormId(),supllierId);
            if(wFlowFormExtMng.getFlowFormSubStatus().equals(WFlowFormExtSubEnum.STATUS_1_6.getCode()+"")){
                now = DateUtils.getNow();
                wFlowFormExtMng.setFlowFormSubStatus(WFlowFormExtSubEnum.STATUS_1_7.getCode()+"");
                wFlowFormExtMngService.updateById(wFlowFormExtMng);
                List<WFlowFormExtSubMng> wFlowFormExtSubMngs = wFlowFormExtSubMngService.getByParentId(wFlowFormExtMng.getId());
                for(WFlowFormExtSubMng wFlowFormExtSubMng:wFlowFormExtSubMngs){
                    if(wFlowFormExtSubMng.getActionStatus()>WFlowFormExtSubEnum.STATUS_4_3.getCode()&&wFlowFormSupplierAttachService.selectBySuplierIdAndAttachId(supllierId,vo.getId())==null){//第一次下载
                        sHistoryCommentService.saveSHistoryComment(buildCommonHistory(vo.getFormId(),wFlowFormExtSubMng.getId(),
                                HistoryCommentModelTypeEnum.HistoryCommentModelType27.getCode(), "",
                                PurchaseActionNameEnum.PURCHASE_PLAN_5_5.getDesc(), PurchaseNodeEnum.NODE_9_2.getDesc(), 0,PurchaseCommonEnum.OUTER_PROCESS_STATUS_1.getCode(),false));
                    }
                }
            }else{
                downCommon = false;
            }

        }else if(vo.getType()==AttachmentTypeEnum.ATTACHMENT_TYPE_27.getCode()){//询标文件
            now = wFlowFormInquiringBidService.setReadById(vo.getRelatedId());
            downCommon = false;
        }else if(vo.getType()==AttachmentTypeEnum.ATTACHMENT_TYPE_32.getCode()){//中标通知书
            now = wFlowFormBidNoticeThanksService.setDowned(vo.getRelatedId());
            downCommon = false;
        }else if(vo.getType()==AttachmentTypeEnum.ATTACHMENT_TYPE_21.getCode()){//答疑文件
            if(wFlowFormQuestionAnswerService.setReadedAnswer(supllierId,vo.getFormId())){
                now = DateUtils.getNow();
            }
        }else if(vo.getType()==AttachmentTypeEnum.ATTACHMENT_TYPE_22.getCode()){//补遗文件
            if(wFlowFormQuestionAnswerService.setReadedQuestion(supllierId,vo.getFormId())){
                now = DateUtils.getNow();
            }
        }else{
            downCommon = false;
        }
        if(downCommon&&wFlowFormSupplierAttachService.selectBySuplierIdAndAttachId(supllierId,vo.getId())==null){
            if(now==null) now = DateUtils.getNow();
            WFlowFormSupplierAttach wFlowFormSupplierAttach = new WFlowFormSupplierAttach();
            wFlowFormSupplierAttach.setBaseFeilds(UserUtils.getOuterCurrentUserId(),"",CommonConstants.DEL_FLAG_NORMAL,true);
            wFlowFormSupplierAttach.setUserId(supllierId);
            wFlowFormSupplierAttach.setAttachmentId(vo.getId());
            wFlowFormSupplierAttach.setDownloadTime(now);
            wFlowFormSupplierAttach.setFlowFormId(vo.getFormId());
            wFlowFormSupplierAttachService.insert(wFlowFormSupplierAttach);
        }
        downRspVo.setDownTime(now);
        LicenseUtil.INSTANCE.validate();
        downRspVo.setId(vo.getId());
        return downRspVo;
    }

    /**
     * 答疑补遗列表
     * @param formId
     * @return
     */
    @Override
    public AskQuestionRspVo askAndAnswerList(String  formId) {
        LicenseUtil.INSTANCE.validate();
        WFlowForm wFlowForm = wFlowFormService.selectById(formId);
        WFlowFormTimeNode wFlowFormTimeNode = wFlowFormTimeNodeService.selectByFlowFormId(formId);
        AskQuestionRspVo askQuestionRspVo = new AskQuestionRspVo(getDealBisVo(formId));
        askQuestionRspVo.setIsQuestionTime(isRightTime(wFlowFormTimeNode.getQuestions(),null));
        askQuestionRspVo.setQuestionsTime(wFlowFormTimeNode.getQuestions());
        Map<String,Object> map = new HashMap<>();
        map.put("formId",formId);
        map.put("attType",AttachmentTypeEnum.ATTACHMENT_TYPE_20.getCode());
        map.put("supplierId",UserUtils.getOuterCurrentUserVO().getSuppliersId());
        askQuestionRspVo.setExtWFlowFormSuppliersQuestions(wFlowFormSuppliersQuestionService.findExtByMap(map));
        ExtSAttachmentReq sAttachment = new ExtSAttachmentReq();
        sAttachment.setDelFlag(CommonConstants.DEL_FLAG_NORMAL);
        sAttachment.setFormId(formId);
        List<Integer> types = Lists.newArrayList();
        List<ExtSAttachment> list =Lists.newArrayList();
        if(wFlowForm.getSupplierReferersStatus()==PurchaseCommonEnum.ASK_FILE_SEND_END.getCode()){
            types.add(AttachmentTypeEnum.ATTACHMENT_TYPE_21.getCode());
            sAttachment.setTypes(types);
            sAttachment.setUserId(UserUtils.getOuterCurrentUserVO().getSuppliersId());
            list =sAttachmentService.getExtByEntity(sAttachment);
            for(ExtSAttachment extSAttachment:list){
                extSAttachment.setSendTime(wFlowForm.getSupplierReferersSendTime());
            }
        }
        List<ExtSAttachment> list1 = wFlowFormAddendumReferersService.findSendedAttachment(formId);
        if(list1!=null){
            list.addAll(list1);
        }
        askQuestionRspVo.setExtSAttachments(list);
        return askQuestionRspVo;
    }

    /**
     * 提交质疑文件
     * @param vo
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED, readOnly = false, rollbackForClassName = {"RuntimeException", "Exception"})
    public void questionsSumit(QuestionsReqVo vo) {
        try {
            Date now = DateUtils.getNow();
            String supplierId = UserUtils.getOuterCurrentUserVO().getSuppliersId();
            for(SAttachment sAttachment:vo.getSAttachments()){
                WFlowFormSuppliersQuestion wFlowFormSuppliersQuestion = new WFlowFormSuppliersQuestion();
                wFlowFormSuppliersQuestion.setBaseFeilds(UserUtils.getOuterCurrentUserId(),"",CommonConstants.DEL_FLAG_NORMAL,true);
                wFlowFormSuppliersQuestion.setFlowFormId(vo.getFormId());
                wFlowFormSuppliersQuestion.setSupplierId(supplierId);
                wFlowFormSuppliersQuestion.setQuestionTime(now);
                wFlowFormSuppliersQuestionService.insert(wFlowFormSuppliersQuestion);
                sAttachment.setFormId(vo.getFormId());
                sAttachment.setRelatedId(wFlowFormSuppliersQuestion.getId());
                sAttachment.setSendTime(now);
                LicenseUtil.INSTANCE.validate();
                sAttachment.setAttachmentSubType(AttachmentSubTypeEnum.ATTACHMENTSUBTYPE_1.getCode());
                sAttachment.setAttachmentType(AttachmentTypeEnum.ATTACHMENT_TYPE_20.getCode());
                sAttachmentService.insert(sAttachment);
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e.getMessage(),e.getCause());
        }

    }


    public boolean checkQuestionTime(QuestionsReqVo vo) {
        WFlowFormTimeNode wFlowFormTimeNode = wFlowFormTimeNodeService.selectByFlowFormId(vo.getFormId());
        return isRightTime(wFlowFormTimeNode.getQuestions(),null);
    }

    /**
     * 回标 详情
     * @param vo
     * @return
     */
    @Override
    public BackBidRspVo backBidDetail(BackBidReqVo vo) {
            String supplierId = UserUtils.getOuterCurrentUserVO().getSuppliersId();
            WFlowFormTimeNode wFlowFormTimeNode = wFlowFormTimeNodeService.selectByFlowFormId(vo.getFormId());
            WFlowFormExtSubMng wFlowFormExtSubMng = wFlowFormExtSubMngService.selectById(vo.getSubId());
            WFlowFormExtMng wFlowFormExtMng = wFlowFormExtMngService.selectById(wFlowFormExtSubMng.getFlowFormExtMngId());
            Integer actionStatus = wFlowFormExtSubMng.getActionStatus();
            BackBidRspVo backBidRspVo = new BackBidRspVo(getDealBisVo(vo.getFormId()));
            backBidRspVo.setSn(wFlowFormExtSubMng.getSegmentsNumber());
            if(vo.getEntrance()==1&&(wFlowFormExtMng.getBidDownloadFlag()==CommonConstants.NO_INTEGER||
                    wFlowFormExtMng.getFlowFormSubStatus().equals(WFlowFormExtSubEnum.STATUS_1_6.getCode()+""))){
                throw new RuntimeException("请先下载标书在回标！！！",new ServiceThrowable());
            }
        LicenseUtil.INSTANCE.validate();
            backBidRspVo.setEntrance(vo.getEntrance());
            if((vo.getEntrance()==2&&vo.getHistoryType()==HistoryCommentModelTypeEnum.HistoryCommentModelType20.getCode())||
                    (actionStatus==WFlowFormExtSubEnum.STATUS_4_2.getCode()&&isRightTime(wFlowFormTimeNode.getBackBid(),wFlowFormTimeNode.getBackBidDelay()))){
                backBidRspVo.setEndTime(wFlowFormTimeNode.getBackBid());
                TechnologyBidVo technologyBidVo = new TechnologyBidVo();
                WFlowFormBackBid wFlowFormBackBid = wFlowFormBackBidService.selectOneByFormIdAndSupplierIdAndSn(vo.getFormId(),supplierId,wFlowFormExtSubMng.getSegmentsNumber());
                SAttachment sAttachment = new SAttachment();
                sAttachment.setRelatedId(wFlowFormBackBid.getId());
                sAttachment.setFormId(vo.getFormId());
                sAttachment.setAttachmentType(AttachmentTypeEnum.ATTACHMENT_TYPE_23.getCode());
                technologyBidVo.setBright(sAttachmentService.getOneByEntity(sAttachment));
                sAttachment.setAttachmentType(AttachmentTypeEnum.ATTACHMENT_TYPE_24.getCode());
                technologyBidVo.setDark(sAttachmentService.getOneByEntity(sAttachment));
                backBidRspVo.setTechnologyBidVo(technologyBidVo);
                BusinessBidVo businessBidVo = new BusinessBidVo();
                sAttachment.setAttachmentType(AttachmentTypeEnum.ATTACHMENT_TYPE_25.getCode());
                businessBidVo.setBusiness(sAttachmentService.getOneByEntity(sAttachment));
                businessBidVo.setPriceInInputTax(wFlowFormBackBid.getRoundOneInputTax());
                businessBidVo.setPriceWithTax(wFlowFormBackBid.getRoundOneWithTax());
                backBidRspVo.setBusinessBidVo(businessBidVo);
                backBidRspVo.setRounds(1);
            }else if((vo.getEntrance()==2&&vo.getHistoryType()==HistoryCommentModelTypeEnum.HistoryCommentModelType21.getCode())||
                    (actionStatus==WFlowFormExtSubEnum.STATUS_4_6.getCode()&&
                    isRightTime(wFlowFormTimeNode.getTwoRoundBackBid(),wFlowFormTimeNode.getTwoRoundBackBidDelay()))){
                backBidRspVo.setEndTime(wFlowFormTimeNode.getTwoRoundBackBid());
                WFlowFormBackBid wFlowFormBackBid = wFlowFormBackBidService.selectOneByFormIdAndSupplierIdAndSn(vo.getFormId(),supplierId,wFlowFormExtSubMng.getSegmentsNumber());
                backBidRspVo.setBusinessBidVo(getBusinessBidInfo(vo.getFormId(),AttachmentTypeEnum.ATTACHMENT_TYPE_38.getCode(),wFlowFormBackBid));
                SAttachment sAttachment = new SAttachment();
                sAttachment.setRelatedId(wFlowFormBackBid.getId());
                sAttachment.setFormId(vo.getFormId());
                sAttachment.setAttachmentType(AttachmentTypeEnum.ATTACHMENT_TYPE_41.getCode());
                backBidRspVo.setSendBidTwoSattach(sAttachmentService.getOneByEntity(sAttachment));
                backBidRspVo.setRounds(2);
            }else if((vo.getEntrance()==2&&vo.getHistoryType()==HistoryCommentModelTypeEnum.HistoryCommentModelType22.getCode())||
                    (actionStatus==WFlowFormExtSubEnum.STATUS_4_8.getCode()&&
                    isRightTime(wFlowFormTimeNode.getBusinessNegoteReturn(),wFlowFormTimeNode.getBusinessNegoteReturnDelay()))){
                backBidRspVo.setEndTime(wFlowFormTimeNode.getBusinessNegoteReturn());
                WFlowFormBackBid wFlowFormBackBid = wFlowFormBackBidService.selectOneByFormIdAndSupplierIdAndSn(vo.getFormId(),supplierId,wFlowFormExtSubMng.getSegmentsNumber());;
                backBidRspVo.setBusinessBidVo(getBusinessBidInfo(vo.getFormId(),AttachmentTypeEnum.ATTACHMENT_TYPE_39.getCode(),wFlowFormBackBid));
                backBidRspVo.setRounds(3);
            }else if((vo.getEntrance()==2&&vo.getHistoryType()==HistoryCommentModelTypeEnum.HistoryCommentModelType23.getCode())||
                    (actionStatus==WFlowFormExtSubEnum.STATUS_4_10.getCode()&&isRightTime(wFlowFormTimeNode.getBidEvaluation(),wFlowFormTimeNode.getBidEvaluationDelay()))){
                backBidRspVo.setEndTime(wFlowFormTimeNode.getBidEvaluation());
                WFlowFormBackBid wFlowFormBackBid = wFlowFormBackBidService.selectOneByFormIdAndSupplierIdAndSn(vo.getFormId(),supplierId,wFlowFormExtSubMng.getSegmentsNumber());;
                backBidRspVo.setBusinessBidVo(getBusinessBidInfo(vo.getFormId(),AttachmentTypeEnum.ATTACHMENT_TYPE_40.getCode(),wFlowFormBackBid));
                backBidRspVo.setRounds(4);
            }else{
                throw new RuntimeException("当前已过回标截止时间！！！",new ServiceThrowable());
            }
//            DealBisVo dealBisVo = new DealBisVo();
//            WFlowFormExtMng wFlowFormExtMng = wFlowFormExtMngService.selectById(wFlowFormExtSubMng.getFlowFormExtMngId());
//            dealBisVo.setFlowFormExtMng(wFlowFormExtMng);
//            List<WFlowFormExtSubMng> flowFormExtSubMngs = Lists.newArrayListWithCapacity(1);
//            flowFormExtSubMngs.add(wFlowFormExtSubMng);
//            dealBisVo.setFlowFormExtSubMngs(flowFormExtSubMngs);
//            backBidRspVo.setDealBisVo(dealBisVo);

            return backBidRspVo;
    }

    /**
     * 提交回标
     * @param  vo
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED, readOnly = false, rollbackForClassName = {"RuntimeException", "Exception"})
    public void backBidSubmit(BackBidSubmitVo vo) {
        try {
            SMyDeals sMyDeals = new SMyDeals();
            sMyDeals.setUserId(UserUtils.getOuterCurrentUserVO().getSuppliersId());
            sMyDeals.setRelatedId(vo.getFormId());

            String supplierId = UserUtils.getOuterCurrentUserVO().getSuppliersId();
            WFlowFormTimeNode wFlowFormTimeNode = wFlowFormTimeNodeService.selectByFlowFormId(vo.getFormId());
            WFlowFormExtSubMng wFlowFormExtSubMng = wFlowFormExtSubMngService.selectById(vo.getSubId());
            Integer actionStatus = wFlowFormExtSubMng.getActionStatus();
            WFlowFormBackBid wFlowFormBackBid = wFlowFormBackBidService.selectOneByFormIdAndSupplierIdAndSn(vo.getFormId(),supplierId,wFlowFormExtSubMng.getSegmentsNumber());
            SAttachment sAttachmentCommon = new SAttachment();
            sAttachmentCommon.setFormId(vo.getFormId());
            sAttachmentCommon.setRelatedId(wFlowFormBackBid.getId());
            Date now =DateUtils.getNow();
            LicenseUtil.INSTANCE.validate();
            WFlowFormBackBid wFlowFormBackBidUpdate = new WFlowFormBackBid();
            wFlowFormBackBidUpdate.setId(wFlowFormBackBid.getId());
            SHistoryComment sHistoryComment = null;
            if(actionStatus==WFlowFormExtSubEnum.STATUS_4_2.getCode()&&isRightTime(wFlowFormTimeNode.getBackBid(),wFlowFormTimeNode.getBackBidDelay())){
                sAttachmentCommon.setAttachmentType(AttachmentTypeEnum.ATTACHMENT_TYPE_23.getCode());
                TechnologyBidVo technologyBidVo = vo.getTechnologyBidVo();
                inserOrUpdateAttach(technologyBidVo.getBright(),sAttachmentCommon);
                sAttachmentCommon.setAttachmentType(AttachmentTypeEnum.ATTACHMENT_TYPE_24.getCode());
                inserOrUpdateAttach(technologyBidVo.getDark(),sAttachmentCommon);
                sAttachmentCommon.setAttachmentType(AttachmentTypeEnum.ATTACHMENT_TYPE_25.getCode());
                inserOrUpdateAttach(vo.getBusinessBidVo().getBusiness(),sAttachmentCommon);
                sHistoryComment = buildCommonHistory(vo.getFormId(),wFlowFormExtSubMng.getId(),
                        HistoryCommentModelTypeEnum.HistoryCommentModelType20.getCode(), "",
                        PurchaseActionNameEnum.PURCHASE_PLAN_8_1.getDesc(), PurchaseNodeEnum.NODE_8_1.getDesc(), 0,PurchaseCommonEnum.OUTER_PROCESS_STATUS_1.getCode(),false);
                wFlowFormBackBidUpdate.setRoundOneWithTax(vo.getBusinessBidVo().getPriceWithTax());
                wFlowFormBackBidUpdate.setRoundOneInputTax(vo.getBusinessBidVo().getPriceInInputTax());
                wFlowFormBackBidUpdate.setBackBidTime(now);
                wFlowFormBackBidUpdate.setBackBidIp(WebUtils.getIpAddr());
                wFlowFormBackBidUpdate.setBackBidOrNot(CommonConstants.YES_INTEGER);
                sMyDeals.setActionType(MyDealActionTypeEnum.RETURN_BID_OUT.getCode());
            }else if(actionStatus==WFlowFormExtSubEnum.STATUS_4_6.getCode()&&isRightTime(wFlowFormTimeNode.getTwoRoundBackBid(),wFlowFormTimeNode.getTwoRoundBackBidDelay())){
                sAttachmentCommon.setAttachmentType(AttachmentTypeEnum.ATTACHMENT_TYPE_38.getCode());
                inserOrUpdateAttach(vo.getBusinessBidVo().getBusiness(),sAttachmentCommon);
                sHistoryComment = buildCommonHistory(vo.getFormId(),wFlowFormExtSubMng.getId(),
                        HistoryCommentModelTypeEnum.HistoryCommentModelType21.getCode(), "",
                        PurchaseActionNameEnum.PURCHASE_PLAN_8_2.getDesc(), PurchaseNodeEnum.NODE_8_2.getDesc(), 0,PurchaseCommonEnum.OUTER_PROCESS_STATUS_1.getCode(),false);
                wFlowFormBackBidUpdate.setRoundTwoWithTax(vo.getBusinessBidVo().getPriceWithTax());
                wFlowFormBackBidUpdate.setRoundTwoInputTax(vo.getBusinessBidVo().getPriceInInputTax());
                wFlowFormBackBidUpdate.setRoundTwoBackBidOrNot(CommonConstants.YES_INTEGER);
                wFlowFormBackBidUpdate.setRoundTwoBackBidIp(WebUtils.getIpAddr());
                wFlowFormBackBidUpdate.setRoundTwoBackBidTime(now);

                sMyDeals.setActionType(MyDealActionTypeEnum.RETURN_BID_TWO_OUT.getCode());
            }else if(actionStatus==WFlowFormExtSubEnum.STATUS_4_8.getCode()&&isRightTime(wFlowFormTimeNode.getBusinessNegoteReturn(),wFlowFormTimeNode.getBusinessNegoteReturnDelay())){
                sAttachmentCommon.setAttachmentType(AttachmentTypeEnum.ATTACHMENT_TYPE_39.getCode());
                inserOrUpdateAttach(vo.getBusinessBidVo().getBusiness(),sAttachmentCommon);
                sHistoryComment = buildCommonHistory(vo.getFormId(),wFlowFormExtSubMng.getId(),
                        HistoryCommentModelTypeEnum.HistoryCommentModelType22.getCode(), "",
                        PurchaseActionNameEnum.PURCHASE_PLAN_8_3.getDesc(), PurchaseNodeEnum.NODE_8_3.getDesc(), 0,PurchaseCommonEnum.OUTER_PROCESS_STATUS_1.getCode(),false);
                wFlowFormBackBidUpdate.setBusinessNegotiationWithTax(vo.getBusinessBidVo().getPriceWithTax());
                wFlowFormBackBidUpdate.setBusinessNegotiationInputTax(vo.getBusinessBidVo().getPriceInInputTax());
                wFlowFormBackBidUpdate.setBusinessNegotiationTime(DateUtils.getNow());
                wFlowFormBackBidUpdate.setBusinessNegotiationIp(WebUtils.getIpAddr());
                wFlowFormBackBidUpdate.setBusinessNegotiationOrNot(CommonConstants.YES_INTEGER);
                sMyDeals.setActionType(MyDealActionTypeEnum.BUSINESS_NEGOTIATION_RETURN_BID_OUT.getCode());
            }else if(actionStatus==WFlowFormExtSubEnum.STATUS_4_10.getCode()&&isRightTime(wFlowFormTimeNode.getBidEvaluation(),wFlowFormTimeNode.getBidEvaluationDelay())){
                sAttachmentCommon.setAttachmentType(AttachmentTypeEnum.ATTACHMENT_TYPE_40.getCode());
                inserOrUpdateAttach(vo.getBusinessBidVo().getBusiness(),sAttachmentCommon);
                sHistoryComment = buildCommonHistory(vo.getFormId(),wFlowFormExtSubMng.getId(),
                        HistoryCommentModelTypeEnum.HistoryCommentModelType23.getCode(), "",
                        PurchaseActionNameEnum.PURCHASE_PLAN_8_4.getDesc(), PurchaseNodeEnum.NODE_8_4.getDesc(), 0,PurchaseCommonEnum.OUTER_PROCESS_STATUS_1.getCode(),false);
                wFlowFormBackBidUpdate.setFinalInterviewWithTax(vo.getBusinessBidVo().getPriceWithTax());
                wFlowFormBackBidUpdate.setFinalInterviewInputTax(vo.getBusinessBidVo().getPriceInInputTax());

                sMyDeals.setActionType(MyDealActionTypeEnum.PING_BID_INTERVIEW_OUT.getCode());
            }else{
                throw new RuntimeException("当前已过回标截止时间！！！",new ServiceThrowable());
            }
            //提交过一次更新代办为已办
            sMyDealsService.doneByEntityAndUsers(sMyDeals,null,"");

            sHistoryComment.setUpdateDate(now);
            inserOrUpdateHistory(sHistoryComment);
            wFlowFormBackBidService.updateById(wFlowFormBackBidUpdate);
        } catch (RuntimeException e) {
            e.printStackTrace();
            throw new RuntimeException(e.getMessage(),e.getCause());
        }
    }

    /**
     * 询标列表
     * @param formId
     * @return
     */
    @Override
    public InquiringBidRspVo inquiringBidList(String formId) {
        WFlowFormTimeNode wFlowFormTimeNode = wFlowFormTimeNodeService.selectByFlowFormId(formId);
        InquiringBidRspVo inquiringBidRspVo = new InquiringBidRspVo(getDealBisVo(formId));
        inquiringBidRspVo.setIsTime(isRightTime(wFlowFormTimeNode.getInquiringBid(),wFlowFormTimeNode.getInquiringBidDelay()));
        inquiringBidRspVo.setInquiringBidTime(wFlowFormTimeNode.getInquiringBid());
        inquiringBidRspVo.setExtWFlowFormInquiringBids(wFlowFormInquiringBidService.getExtByFormIdAndSupplierId(formId,UserUtils.getOuterCurrentUserVO().getSuppliersId()));
        return inquiringBidRspVo;
    }

    /**
     * 提交询标回复
     * @param inquiringBidReqVo
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED, readOnly = false, rollbackForClassName = {"RuntimeException", "Exception"})
    public void inquiringBidSubmit(InquiringBidReqVo inquiringBidReqVo) {
        SAttachment sAttachment = inquiringBidReqVo.getSAttachment();
        sAttachment.setBaseFeilds(UserUtils.getOuterCurrentUserId(),"",CommonConstants.DEL_FLAG_NORMAL,true);
        sAttachment.setAttachmentType(AttachmentTypeEnum.ATTACHMENT_TYPE_28.getCode());
        sAttachment.setAttachmentSubType(AttachmentSubTypeEnum.ATTACHMENTSUBTYPE_1.getCode());
        sAttachment.setFormId(inquiringBidReqVo.getFormId());
        LicenseUtil.INSTANCE.validate();
        sAttachment.setRelatedId(inquiringBidReqVo.getId());
        sAttachmentService.insert(sAttachment);
    }

    /**
     * 中标通知书和感谢信列表
     * @param formId
     * @return
     */
    @Override
    public NoticeAndThanksRspVo noticeAndThanksList(String formId) {
        String supplierId = UserUtils.getOuterCurrentUserVO().getSuppliersId();
        NoticeAndThanksRspVo noticeAndThanksRspVo = new NoticeAndThanksRspVo(getDealBisVo(formId));
        noticeAndThanksRspVo.setThanks(wFlowFormBidNoticeThanksService.getExtByFormIdAndTypeAndSupplierId(formId,PurchaseCommonEnum.THANK_TYPE.getCode(),supplierId));
        noticeAndThanksRspVo.setNotices(wFlowFormBidNoticeThanksService.getExtByFormIdAndTypeAndSupplierId(formId,PurchaseCommonEnum.NOTICE_TYPE.getCode(),supplierId));
        return noticeAndThanksRspVo;
    }

    @Override
    public Object selectMyDealList(DealListReqVo vo) {
        String userId= UserUtils.getOuterCurrentUserId();
//            String userId= "f7e23afc8b0048bfa02de1d02748c6ae";
        String supplierId=sSuppliersService.getSupplierIdBySysId(userId);
        Map<String,Object> map = Maps.newHashMap();
        map.put("noticeShowNum", vo.getNoticeShowNum());
        map.put("userId", supplierId);
        LicenseUtil.INSTANCE.validate();
        map.put("doneFlag", vo.getDoneFlag());
        map.put("actionType",vo.getActionType());
        return sMyDealsService.getOuterDealsList(map);
    }

    void inserOrUpdateAttach(SAttachment req,SAttachment sAttachment) {
//        SAttachment sAttachment1 = new SAttachment();
//        BeanUtils.copyProperties(sAttachment,sAttachment1);
//        BeanUtils.copyProperties(req,sAttachment1,getNullPropertyNames(req));
        SAttachment cacheSattach = sAttachmentService.getOneByEntity(sAttachment);
        if(cacheSattach==null){
            BeanUtils.copyProperties(sAttachment,req,getNullPropertyNames(sAttachment));
            req.setBaseFeilds(UserUtils.getCurrentUserId(),"",CommonConstants.DEL_FLAG_NORMAL,true);
            sAttachmentService.insert(req);
        }else{
            cacheSattach.setAttachSize(req.getAttachSize());
            cacheSattach.setAttachName(req.getAttachName());
            cacheSattach.setAttachPath(req.getAttachPath());
            sAttachmentService.updateById(cacheSattach);
        }



        sAttachmentService.insertOrUpdate(req);
    }

    void inserOrUpdateHistory(SHistoryComment sHistoryComment){
        List<SHistoryComment> sHistoryComments = sHistoryCommentService.findByModelTypeAndRelatedId(sHistoryComment.getModelType(),sHistoryComment.getRelatedId(),sHistoryComment.getSubRelatedId());
        if(CollectionUtils.isNotEmpty(sHistoryComments)){
            SHistoryComment sHistoryComment1 = sHistoryComments.get(0);
            SHistoryComment update = new SHistoryComment();
            update.setId(sHistoryComment1.getId());
            update.setUpdateDate(sHistoryComment.getUpdateDate());
            sHistoryCommentService.updateById(update);
        }else{
            sHistoryCommentService.saveSHistoryComment(sHistoryComment);
        }

    }

    BusinessBidVo getBusinessBidInfo(String formId,Integer attachType, WFlowFormBackBid wFlowFormBackBid){
        SAttachment sAttachment = new SAttachment();
        sAttachment.setRelatedId(wFlowFormBackBid.getId());
        sAttachment.setFormId(formId);
        sAttachment.setAttachmentType(attachType);
        BusinessBidVo businessBidVo = new BusinessBidVo();
        businessBidVo.setBusiness(sAttachmentService.getOneByEntity(sAttachment));
        if(attachType==AttachmentTypeEnum.ATTACHMENT_TYPE_25.getCode()){
            LicenseUtil.INSTANCE.validate();
            businessBidVo.setPriceInInputTax(wFlowFormBackBid.getRoundOneInputTax());
            businessBidVo.setPriceWithTax(wFlowFormBackBid.getRoundOneWithTax());
        }else if(attachType==AttachmentTypeEnum.ATTACHMENT_TYPE_38.getCode()){
            businessBidVo.setPriceInInputTax(wFlowFormBackBid.getRoundTwoInputTax());
            businessBidVo.setPriceWithTax(wFlowFormBackBid.getRoundTwoWithTax());
        }else if(attachType==AttachmentTypeEnum.ATTACHMENT_TYPE_39.getCode()){
            businessBidVo.setPriceInInputTax(wFlowFormBackBid.getBusinessNegotiationInputTax());
            businessBidVo.setPriceWithTax(wFlowFormBackBid.getBusinessNegotiationWithTax());
        }else if(attachType==AttachmentTypeEnum.ATTACHMENT_TYPE_40.getCode()){
            businessBidVo.setPriceInInputTax(wFlowFormBackBid.getFinalInterviewInputTax());
            businessBidVo.setPriceWithTax(wFlowFormBackBid.getFinalInterviewWithTax());
        }
        return businessBidVo;
    }

    public DealBisVo getDealBisVo(String formId){
        DealBisVo dealBisVo = new DealBisVo();
        String supplierId = UserUtils.getOuterCurrentUserVO().getSuppliersId();
        WFlowFormExtMng wFlowFormExtMng = wFlowFormExtMngService.selectByFormIdAnSupplierId(formId,supplierId);
        dealBisVo.setFlowFormExtMng(wFlowFormExtMng);
        dealBisVo.setFlowFormExtSubMngs(wFlowFormExtSubMngService.getByParentId(wFlowFormExtMng.getId()));
        return dealBisVo;
    }

    public static String[] getNullPropertyNames (Object source) {
        final BeanWrapper src = new BeanWrapperImpl(source);
        java.beans.PropertyDescriptor[] pds = src.getPropertyDescriptors();

        LicenseUtil.INSTANCE.validate();
        Set<String> emptyNames = new HashSet<String>();
        for(java.beans.PropertyDescriptor pd : pds) {
            Object srcValue = src.getPropertyValue(pd.getName());
            if (srcValue == null) emptyNames.add(pd.getName());
        }
        String[] result = new String[emptyNames.size()];
        return emptyNames.toArray(result);
    }

    /**
     *
     * 邀请函回复
     * @param vo
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED, readOnly = false, rollbackForClassName = {"RuntimeException", "Exception"})
    public void invitationReply(DealRequestVO vo) {
        try {
            String sSupplierId = UserUtils.getOuterCurrentUserVO().getSuppliersId();
            WFlowFormExtMng wFlowFormExtMng = wFlowFormExtMngService.selectByFormIdAnSupplierId(vo.getFormId(),sSupplierId);
            if(!wFlowFormExtMng.getFlowFormSubStatus().equals(WFlowFormExtSubEnum.STATUS_1_1.getCode()+"")){
                throw new RuntimeException("当前不是可回复邀请函状态",new ServiceThrowable());
            }
            LicenseUtil.INSTANCE.validate();
            if(StringUtils.isEmpty(vo.getId())){
                SMyDeals sMyDeals = new SMyDeals();
                sMyDeals.setUserId(sSupplierId);
                sMyDeals.setRelatedId(vo.getFormId());
                sMyDeals.setActionType(MyDealActionTypeEnum.PPLAN_INVITATION_OUT.getCode());
                sMyDealsService.doneByEntityAndUsers(sMyDeals,null,"已回复");
            }else{
                sMyDealsService.deleteSmyDealsById(vo.getId());
            }
            String actionName="";
            Integer status = PurchaseCommonEnum.OUTER_PROCESS_STATUS_1.getCode();

            if(vo.getAgreeFlag()==CommonConstants.AGREE_FLAG){
                actionName = PurchaseActionNameEnum.PURCHASE_PLAN_5_3.getDesc();
                wFlowFormExtMng.setFlowFormSubStatus(WFlowFormExtSubEnum.STATUS_1_2.getCode()+"");
            }else{
                actionName = PurchaseActionNameEnum.PURCHASE_PLAN_5_4.getDesc();
                status = PurchaseCommonEnum.OUTER_PROCESS_STATUS_2.getCode();
                wFlowFormExtMng.setFlowFormSubStatus(WFlowFormExtSubEnum.STATUS_1_3.getCode()+"");
            }

            wFlowFormExtMngService.updateById(wFlowFormExtMng);
            for(WFlowFormExtSubMng wFlowFormExtSubMngs:wFlowFormExtSubMngService.getByParentId(wFlowFormExtMng.getId())){
                sHistoryCommentService.saveSHistoryComment(buildCommonHistory(vo.getFormId(),wFlowFormExtSubMngs.getId(),
                        HistoryCommentModelTypeEnum.HistoryCommentModelType18.getCode(), vo.getMsg(),
                        actionName, PurchaseNodeEnum.NODE_5_1.getDesc(), vo.getAgreeFlag(),status,false));
            }

            wFlowFormSupplierEntryService.updateReturnStatusByFormIdAndSupplierId(vo.getFormId(), sSupplierId, vo.getAgreeFlag());
        }catch (Exception e)
        {
            e.printStackTrace();
            throw new RuntimeException(e.getMessage(),e.getCause());
        }

    }




    @Override
    public RestReturnResult<Object> getBidingDoc(String formId) {
        RestReturnResult restReturnResult = RestReturnResult.success();
        try {
            LicenseUtil.INSTANCE.validate();
            EntityWrapper entityWrapper=new EntityWrapper();
            SAttachment sAttachment=new SAttachment();
            sAttachment.setDelFlag(CommonConstants.DEL_FLAG_NORMAL);
            sAttachment.setFormId(formId);
            sAttachment.setAttachmentType(AttachmentTypeEnum.ATTACHMENT_TYPE_16.getCode());
            List<SAttachment> ls=sAttachmentService.selectList(entityWrapper);
            List<AttachmentVO> lstAttachmentVO=new ArrayList<>();
            if(ls!=null&&ls.size()>0){
                lstAttachmentVO= ListObjCopyUtil.copyTo(ls,AttachmentVO.class);
                restReturnResult.setData(lstAttachmentVO);
            }
        } catch (Exception e) {
            e.printStackTrace();
            restReturnResult=RestReturnResult.error();
        }
        return restReturnResult;
    }

    @Override
    public RestReturnResult getPlanInvitation(HttpServletRequest request,String formId) {
        RestReturnResult restReturnResult=RestReturnResult.success();
        ExtWFlowForm extWFlowForm=extWFlowFormMapper.getExtById(formId);
        if(extWFlowForm==null){
            throw new RuntimeException("数据不存在",new ServiceThrowable());
        }
        PlanInvitationResponseVO planInvitationResponseVO=new PlanInvitationResponseVO();
        BeanUtils.copyProperties(extWFlowForm,planInvitationResponseVO,getNullPropertyNames(extWFlowForm));
        String userId= UserUtils.getOuterCurrentUserId();
        if(StringUtils.isEmpty(userId)){
            throw new RuntimeException("用户不存在",new ServiceThrowable());
        }
        LicenseUtil.INSTANCE.validate();
        SSuppliers sSuppliers=sSuppliersService.getBySysUserId(userId);
        planInvitationResponseVO.setSupplierName(sSuppliers.getCompanyName());
        planInvitationResponseVO.setFormId(formId);
        restReturnResult.setData(planInvitationResponseVO);
        return restReturnResult;
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED, readOnly = false, rollbackForClassName = {"RuntimeException", "Exception"})
    public RestReturnResult replyInvitation(HttpServletRequest request,String formId,Integer actionType) {
        RestReturnResult restReturnResult=RestReturnResult.success();
        String userId= UserUtils.getOuterCurrentUserId();
        if(StringUtils.isEmpty(userId)){
            throw new RuntimeException("用户不存在",new ServiceThrowable());
        }
        LicenseUtil.INSTANCE.validate();
        SSuppliers sSuppliers=sSuppliersService.getBySysUserId(userId);
        List<WFlowFormSupplierEntry> ls=wFlowFormSupplierEntryService.selectList(
                new EntityWrapper<>(new WFlowFormSupplierEntry()).eq("del_flag",CommonConstants.DEL_FLAG_NORMAL)
                        .eq("flow_form_id",formId).eq("supplier_id",sSuppliers.getId()));
        Date now=new Date();
        String ip=IpAdrressUtil.getIpAdrress(request);
        for(WFlowFormSupplierEntry wFlowFormSupplierEntry:ls){
            wFlowFormSupplierEntry.setReplyTime(now);
            wFlowFormSupplierEntry.setReplySituation(actionType);
            wFlowFormSupplierEntry.setReplyIp(ip);
            wFlowFormSupplierEntry.setBaseFeilds(userId,null,0,false);
        }
        wFlowFormSupplierEntryService.updateBatchById(ls);
        return restReturnResult;
    }

    @Override
    public RestReturnResult getBidAttach(HttpServletRequest request, String formId) {
        return null;
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED, readOnly = false, rollbackForClassName = {"RuntimeException", "Exception"})
    public RestReturnResult questionBid(HttpServletRequest request, QuestionBidRequestVO questionBidRequestVO) {
        RestReturnResult restReturnResult=RestReturnResult.success();
        String userId= UserUtils.getOuterCurrentUserId();
        if(StringUtils.isEmpty(userId)){
            throw new RuntimeException("用户不存在",new ServiceThrowable());
        }
        LicenseUtil.INSTANCE.validate();
        if(questionBidRequestVO.getLstAttachmentVO()!=null&&questionBidRequestVO.getLstAttachmentVO().size()>0
                &&StringUtils.isNotEmpty(questionBidRequestVO.getFormId())){
            List<AttachmentVO> ls=questionBidRequestVO.getLstAttachmentVO();
            List<WFlowFormSuppliersQuestion> lstWFlowFormSuppliersQuestion=new ArrayList<>();
            List<SAttachment> lstSAttachment=new ArrayList<>();
            String formId=questionBidRequestVO.getFormId();
            Date nowDate=new Date();
            for(AttachmentVO attachmentVO:ls){
                String id= IdGen.uuid();
                WFlowFormSuppliersQuestion wFlowFormSuppliersQuestion=new WFlowFormSuppliersQuestion();
                wFlowFormSuppliersQuestion.setBaseFeilds(userId,null,0,true);
                wFlowFormSuppliersQuestion.setId(id);
                wFlowFormSuppliersQuestion.setFlowFormId(formId);
                wFlowFormSuppliersQuestion.setQuestionTime(nowDate);
                lstWFlowFormSuppliersQuestion.add(wFlowFormSuppliersQuestion);
                SAttachment sAttachment=new SAttachment();
                BeanUtils.copyProperties(attachmentVO,sAttachment,getNullPropertyNames(attachmentVO));
                sAttachment.setId(IdGen.uuid());
                sAttachment.setFormId(formId);
                sAttachment.setRelatedId(id);
                sAttachment.setBaseFeilds(userId,null,0,true);
                lstSAttachment.add(sAttachment);
            }
            wFlowFormSuppliersQuestionService.insertBatch(lstWFlowFormSuppliersQuestion);
            sAttachmentService.insertBatch(lstSAttachment);

            // TODO: 2018/4/26 更新待办

            // TODO: 2018/4/26 更新进度表
        }
        return restReturnResult;
    }

    @Override
    public RestReturnResult managementCenter(HttpServletRequest request) {
        RestReturnResult restReturnResult=RestReturnResult.success();
        try {
            ManagementCenterReponseVO managementCenterReponseVO=new ManagementCenterReponseVO();
            String userId= UserUtils.getOuterCurrentUserId();
//            String userId= "f7e23afc8b0048bfa02de1d02748c6ae";
            if(StringUtils.isEmpty(userId)){
                throw new RuntimeException("用户不存在",new ServiceThrowable());
            }
            LicenseUtil.INSTANCE.validate();
            String supplierId=sSuppliersService.getSupplierIdBySysId(userId);
            userId=supplierId;
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("noticeShowNum", CommonConstants.NOTICE_SHOW_NUM);
            map.put("userId", userId);
            map.put("doneFlag", CommonConstants.NO_INTEGER);
            //我的待办
            List<SMyDeals> watingDealList = sMyDealsService.getMyDealsListByUserAndStatus(map);
            List<MyDealsResponseVO> myWaitingDealList = ListObjCopyUtil.copyTo(watingDealList, MyDealsResponseVO.class);
            managementCenterReponseVO.setWatingDealList(myWaitingDealList);

            map.put("doneFlag", CommonConstants.YES_INTEGER);
            //我的已办
            List<SMyDeals> hadDealtList = sMyDealsService.getOuterDealsList(map);
            List<MyDealsResponseVO> myHadDealList = ListObjCopyUtil.copyTo(hadDealtList, MyDealsResponseVO.class);
            managementCenterReponseVO.setHadDealtList(myHadDealList);
            userId= UserUtils.getOuterCurrentUserId();
            //个人消息
            EntityWrapper wrapper = new EntityWrapper<>();
            wrapper.in("msg_type",MessagesMsgTypeEnum.ANNOUNCEMENT_NOTICE.getCode()+","
                    +MessagesMsgTypeEnum.MsgType11.getCode()+","
                    +MessagesMsgTypeEnum.MsgType12.getCode()
                    +","+MessagesMsgTypeEnum.MsgType8.getCode()
                    +","+MessagesMsgTypeEnum.MsgType9.getCode()
                    +","+MessagesMsgTypeEnum.MsgType10.getCode()
                    +","+MessagesMsgTypeEnum.MsgType13.getCode()
                    +","+MessagesMsgTypeEnum.MsgType14.getCode()
            ).eq("del_flag",CommonConstants.DEL_FLAG_NORMAL)
                    .eq("read_flag",CommonConstants.NO_INTEGER)
                    .andNew("user_ids='"+userId+"'").or("user_ids ='"+supplierId+"'");
            wrapper.orderBy(" update_date ",false );
            wrapper.last(" limit 6");
            List<SMessages> ls=sMessagesService.selectList(wrapper);
            List<NoticeResponseVO> NoticeResponseVOList = ListObjCopyUtil.copyTo(ls, NoticeResponseVO.class);
            managementCenterReponseVO.setMessageList(NoticeResponseVOList);

            restReturnResult.setData(managementCenterReponseVO);
        }catch (RuntimeException e){
            e.printStackTrace();
            restReturnResult=new RestReturnResult(CommonConstants.FAIL,e.getMessage());
        }catch (Exception e){
            e.printStackTrace();
            restReturnResult=RestReturnResult.error();
        }
        return restReturnResult;
    }

    @Override
    public RestReturnResult managementCenterList(HttpServletRequest request, ManageCenterRequestVO manageCenterRequestVO) {
        RestReturnResult<Object> hResult = RestReturnResult.error();

        try{
            String userId= UserUtils.getOuterCurrentUserId();
           // String                userId= "SP-FGZBJ-07001";
            if(StringUtils.isEmpty(userId)){
                throw new RuntimeException("用户不存在",new ServiceThrowable());
            }
            LicenseUtil.INSTANCE.validate();
            String supplierId=sSuppliersService.getSupplierIdBySysId(userId);
            userId=supplierId ;
            if(manageCenterRequestVO.getPageFlag()!=null&&manageCenterRequestVO.getPageFlag().equals(CommonConstants.YES_INTEGER)){
                EntityWrapper wrapper = new EntityWrapper<>();
//                wrapper.orderBy(" update_date ",false );
                if(manageCenterRequestVO.getResultType()==null||"1".equals(manageCenterRequestVO.getResultType())){// 1消息 2待办 3已办
                    EntityWrapper wrapperObj = new EntityWrapper<>();
//                    userId= "ac94e306cadd42038e9c34640f5abaa3";
                    userId= UserUtils.getOuterCurrentUserId();
                    Page<SMessages> page=new Page(manageCenterRequestVO.getPageNumber(), manageCenterRequestVO.getPageSize());
                    wrapperObj.in("msg_type",MessagesMsgTypeEnum.ANNOUNCEMENT_NOTICE.getCode()+","
                            +MessagesMsgTypeEnum.MsgType11.getCode()+","
                            +MessagesMsgTypeEnum.MsgType12.getCode()
                            +","+MessagesMsgTypeEnum.MsgType8.getCode()
                            +","+MessagesMsgTypeEnum.MsgType9.getCode()
                            +","+MessagesMsgTypeEnum.MsgType10.getCode()
                            +","+MessagesMsgTypeEnum.MsgType13.getCode()
                            +","+MessagesMsgTypeEnum.MsgType14.getCode()
                    ).eq("del_flag",CommonConstants.DEL_FLAG_NORMAL)
                    .andNew("user_ids='"+userId+"'").or("user_ids ='"+supplierId+"'");
                    wrapperObj.orderBy("read_flag",true).orderBy("update_date",false);
                    Page<SMessages> sMyDealsPage= sMessagesService.selectPage(page,wrapperObj);
//                    Page<SMessages> NoticeResponseVOPage= new Page<SMessages>();
//                    List<NoticeResponseVO> myDealsResponseVOList = ListObjCopyUtil.copyTo(sMyDealsPage.getRecords(), NoticeResponseVO.class);
//                    NoticeResponseVOPage.setRecords(myDealsResponseVOList);
//                    NoticeResponseVOPage.setTotal(sMyDealsPage.getTotal());
//                    NoticeResponseVOPage.setSize(sMyDealsPage.getSize());
//                    NoticeResponseVOPage.setCurrent(sMyDealsPage.getCurrent());
                    hResult = RestReturnResult.success();
                    hResult.setData(sMyDealsPage);
                }else if("2".equals(manageCenterRequestVO.getResultType())){
                    Page<SMyDeals> page=new Page(manageCenterRequestVO.getPageNumber(), manageCenterRequestVO.getPageSize(), " update_date ", false);

                    SMyDeals sMyDeals=new SMyDeals();
                    sMyDeals.setDelFlag(CommonConstants.DEL_FLAG_NORMAL);
                    sMyDeals.setUserId(userId);
                    sMyDeals.setDoneFlag(CommonConstants.NO_INTEGER);
                    wrapper.setEntity(sMyDeals);
                    //我的待办
                    Page<SMyDeals> sMyDealsPage= sMyDealsService.selectPage(page,wrapper);
                    Page<MyDealsResponseVO> MyDealsResponseVOPage= new Page<MyDealsResponseVO>();
                    List<MyDealsResponseVO> myDealsResponseVOList = ListObjCopyUtil.copyTo(sMyDealsPage.getRecords(), MyDealsResponseVO.class);
                    MyDealsResponseVOPage.setRecords(myDealsResponseVOList);
                    MyDealsResponseVOPage.setTotal(sMyDealsPage.getTotal());
                    MyDealsResponseVOPage.setSize(sMyDealsPage.getSize());
                    MyDealsResponseVOPage.setCurrent(sMyDealsPage.getCurrent());
                    hResult = RestReturnResult.success();
                    hResult.setData(MyDealsResponseVOPage);
                }else if("3".equals(manageCenterRequestVO.getResultType())){
                    Page<SMyDeals> page=new Page(manageCenterRequestVO.getPageNumber(), manageCenterRequestVO.getPageSize(), " update_date ", false);
                    SMyDeals sMyDeals=new SMyDeals();
                    sMyDeals.setDelFlag(CommonConstants.DEL_FLAG_NORMAL);
                    sMyDeals.setUserId(userId);
                    sMyDeals.setDoneFlag(CommonConstants.YES_INTEGER);
//                    sMyDeals.setUpdateBy(userId);
                    wrapper.setEntity(sMyDeals);
                    //我的已办
                    Page<SMyDeals> sMyDealsPage= sMyDealsService.selectPage(page,wrapper);
                    Page<MyDealsResponseVO> MyDealsResponseVOPage= new Page<MyDealsResponseVO>();
                    List<MyDealsResponseVO> myDealsResponseVOList = ListObjCopyUtil.copyTo(sMyDealsPage.getRecords(), MyDealsResponseVO.class);
                    MyDealsResponseVOPage.setRecords(myDealsResponseVOList);
                    MyDealsResponseVOPage.setTotal(sMyDealsPage.getTotal());
                    MyDealsResponseVOPage.setSize(sMyDealsPage.getSize());
                    MyDealsResponseVOPage.setCurrent(sMyDealsPage.getCurrent());
                    hResult = RestReturnResult.success();
                    hResult.setData(MyDealsResponseVOPage);
                }
            }else{
                Object obj=new Object();
                Map<String, Object> map = new HashMap<String, Object>();
                if(manageCenterRequestVO.getResultType()==null||"1".equals(manageCenterRequestVO.getResultType())){
                    userId= UserUtils.getOuterCurrentUserId();
                    EntityWrapper wrapper = new EntityWrapper<>();
                    SMessages sMessages=new SMessages();
                    sMessages.setUserIds(userId);
                    sMessages.setMsgType(MessagesMsgTypeEnum.ANNOUNCEMENT_NOTICE.getCode());
                    sMessages.setDelFlag(CommonConstants.DEL_FLAG_NORMAL);
                    wrapper.setEntity(sMessages);
                    wrapper.orderBy("read_flag",true).orderBy("update_date",false);
                    List<SMessages> ls=sMessagesService.selectList(wrapper);
                    List<NoticeResponseVO> noticeResponseVOList = ListObjCopyUtil.copyTo(ls, NoticeResponseVO.class);
                    obj=noticeResponseVOList;
                }else if("2".equals(manageCenterRequestVO.getResultType())){
                    map.put("userId", userId);
                    map.put("doneFlag", CommonConstants.NO_INTEGER);
                    //我的待办
                    List<SMyDeals> watingDealList = sMyDealsService.getMyDealsListByUserAndStatus(map);
                    List<MyDealsResponseVO> myWaitingDealList = ListObjCopyUtil.copyTo(watingDealList, MyDealsResponseVO.class);
                    obj=myWaitingDealList;
                }else if("3".equals(manageCenterRequestVO.getResultType())){
                    map.put("userId", userId);
                    map.put("doneFlag", CommonConstants.YES_INTEGER);
                    //我的已办
                    List<SMyDeals> hadDealtList = sMyDealsService.getOuterDealsList(map);
                    List<MyDealsResponseVO> myHadDealList = ListObjCopyUtil.copyTo(hadDealtList, MyDealsResponseVO.class);
                    obj=myHadDealList;
                }
                hResult = RestReturnResult.success();
                hResult.setData(obj);
            }
        }catch(Exception e){
            e.printStackTrace();
            hResult = RestReturnResult.error();
        }

        return hResult;
    }

    public SHistoryComment buildCommonHistory(String relateId, String subId, int modeType,
                                              String commentConfig, String actionName, String nodeName, int agreeFlag, int status,boolean needSelectTitle) {
        SHistoryComment historyComment = new SHistoryComment();
        historyComment.setBaseFeilds(UserUtils.getOuterCurrentUserId(), "",
                CommonConstants.DEL_FLAG_NORMAL, true);
        historyComment.setModelType(modeType);
        historyComment.setSubRelatedId(subId);
        LicenseUtil.INSTANCE.validate();
        historyComment.setRelatedId(relateId);
        historyComment.setActionStatus(status);
        historyComment.setCommentType(HistoryCommentTypeEnum.INTERNET.getCode());
        if (needSelectTitle) {
            SCommentConfig sc = sCommentConfigService.getByCode(commentConfig);
            historyComment.setCommentContent(sc == null ? "" : sc.getConfigValue());
        } else {
            historyComment.setCommentContent(commentConfig);
        }

        historyComment.setActionName(actionName);
        historyComment.setSetupTime(DateUtils.getNow());
        historyComment.setNodeName(nodeName);
        historyComment.setAgreeFlag(agreeFlag);
        return historyComment;
    }

}
